package Dao.Impl;

import Dao.CollectionDao;
import Domain.Collection;
import JDBCUtils.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class CollectionDaoImpl implements CollectionDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Collection> FindCollectionByUserid(int userid) {
        String sql = "select\n" +
                " t.id,t.cid,t.productid,t1.picture,t1.name,t1.price\n" +
                "from\n" +
                " t_collections_product_relation t\n" +
                "join\n" +
                " product t1\n" +
                "on\n" +
                " t.productid = t1.id\n" +
                "where\n" +
                " t.cid=?";
        List<Collection> result = null;
        try {
            result = template.query(sql,new BeanPropertyRowMapper<>(Collection.class),userid);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void DelCollectionById(int id) {
        String sql ="delete from t_collections_product_relation where id=?";
        template.update(sql,id);
    }

    @Override
    public List<Collection> FindCollectionById(int id) {
        String sql ="select\n" +
                " t.id,t.cid,t.productid,t1.picture,t1.name,t1.price\n" +
                "from\n" +
                " t_collections_product_relation t\n" +
                "join\n" +
                " product t1\n" +
                "on\n" +
                " t.productid = t1.id\n" +
                "where\n" +
                " t.id=?";
        List<Collection> result=null;
        try {
            result = template.query(sql,new BeanPropertyRowMapper<>(Collection.class),id);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void AddCollection(int cid, int pid) {
        String sql = "insert into t_collections_product_relation(id,cid,productid) values(null,?,?)";
        template.update(sql,cid,pid);
    }


}
